package com.ouyy.volunteerservice.volunteer.controller;

import com.ouyy.volunteerservice.volunteer.domain.po.Organizations;
import com.ouyy.volunteerservice.volunteer.domain.po.Volunteers;
import com.ouyy.volunteerservice.volunteer.service.OrganizationsService;
import com.ouyy.volunteerservice.volunteer.service.VolunteersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private OrganizationsService organizationsService;

    @PostMapping("/organization/login")
    public ResponseEntity<?> loginOrganization(@RequestBody Organizations organizations) {
        try {
            Organizations foundOrgan = organizationsService.findByOrganAndPassword(organizations.getOrganizationName(), organizations.getPassword());
            if (foundOrgan != null) {
                // 登录成功，返回包含用户名的信息
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("data", foundOrgan);
                return ResponseEntity.ok(response);
            } else {
                // 用户名或密码错误，返回更具体的错误信息
                return ResponseEntity.status(401).body("组织不存在或密码错误！");
            }
        } catch (Exception e) {
            logger.error("登录失败", e);
            // 服务器错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误！");
        }
    }
}
